import React from 'react';
import type { BatchDragState } from '../hooks/useBatchDragDrop';
import { RoomStatusManager } from '../utils/RoomStatusManager';
import styles from '../styles/BatchDragVisualizer.module.css';

interface BatchDragVisualizerProps {
  batchDragState: BatchDragState;
  config: {
    cellWidth: number;
    cellHeight: number;
    roomTypeWidth: number;
    roomNumberWidth: number;
  };
  rooms: Array<{ id: string; roomNumber: string }>;
  dates: string[];
}

const BatchDragVisualizer: React.FC<BatchDragVisualizerProps> = ({
  batchDragState,
  config,
  rooms,
  dates,
}) => {
  console.log('🎨 BatchDragVisualizer 渲染:', {
    isActive: batchDragState.isActive,
    previewDataLength: batchDragState.previewData.length,
    sourceItemsLength: batchDragState.sourceItems.length,
  });

  if (!batchDragState.isActive || batchDragState.previewData.length === 0) {
    console.log(
      '❌ BatchDragVisualizer 不显示: isActive=',
      batchDragState.isActive,
      'previewData=',
      batchDragState.previewData.length
    );
    return null;
  }

  console.log('✅ BatchDragVisualizer 开始渲染连接线');

  return (
    <div className={styles.visualizer}>
      {/* 拖拽预览连接线 */}
      <svg
        className={styles.connectionLines}
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          pointerEvents: 'none',
          zIndex: 999,
        }}
      >
        {batchDragState.previewData.map((item, index) => {
          const sourceRoomIndex = rooms.findIndex(
            r => r.id === item.sourceRoom.id
          );
          const sourceDateIndex = dates.findIndex(d => d === item.sourceDate);
          const targetRoomIndex = rooms.findIndex(
            r => r.id === item.targetRoom.id
          );
          const targetDateIndex = dates.findIndex(d => d === item.targetDate);

          if (
            sourceRoomIndex === -1 ||
            sourceDateIndex === -1 ||
            targetRoomIndex === -1 ||
            targetDateIndex === -1
          ) {
            return null;
          }

          // 计算位置
          const sourceX =
            config.roomTypeWidth +
            config.roomNumberWidth +
            sourceDateIndex * config.cellWidth +
            config.cellWidth / 2;
          const sourceY =
            sourceRoomIndex * config.cellHeight + config.cellHeight / 2;
          const targetX =
            config.roomTypeWidth +
            config.roomNumberWidth +
            targetDateIndex * config.cellWidth +
            config.cellWidth / 2;
          const targetY =
            targetRoomIndex * config.cellHeight + config.cellHeight / 2;

          // 连接线颜色
          const strokeColor = item.isValid ? '#28a745' : '#dc3545';
          const strokeOpacity = item.isValid ? 0.8 : 0.6;

          // 计算箭头角度
          const angle = Math.atan2(targetY - sourceY, targetX - sourceX);
          const arrowLength = 12;

          return (
            <g key={index}>
              {/* 连接线 */}
              <line
                x1={sourceX}
                y1={sourceY}
                x2={targetX}
                y2={targetY}
                stroke={strokeColor}
                strokeWidth='3'
                strokeOpacity={strokeOpacity}
                strokeDasharray='8,4'
                className={styles.connectionLine}
              />

              {/* 箭头 */}
              <polygon
                points={`${targetX},${targetY} ${targetX - arrowLength * Math.cos(angle - Math.PI / 6)},${targetY - arrowLength * Math.sin(angle - Math.PI / 6)} ${targetX - arrowLength * Math.cos(angle + Math.PI / 6)},${targetY - arrowLength * Math.sin(angle + Math.PI / 6)}`}
                fill={strokeColor}
                fillOpacity={strokeOpacity}
                className={styles.arrow}
              />

              {/* 源点标记 */}
              <circle
                cx={sourceX}
                cy={sourceY}
                r='6'
                fill='#007bff'
                fillOpacity='0.8'
                stroke='white'
                strokeWidth='2'
                className={styles.sourcePoint}
              />

              {/* 目标点标记 */}
              <circle
                cx={targetX}
                cy={targetY}
                r='8'
                fill={strokeColor}
                fillOpacity='0.9'
                stroke='white'
                strokeWidth='2'
                className={styles.targetPoint}
              />
            </g>
          );
        })}
      </svg>

      {/* 目标位置预览 */}
      {batchDragState.previewData.map((item, index) => {
        if (!item.isValid) return null;

        const targetRoomIndex = rooms.findIndex(
          r => r.id === item.targetRoom.id
        );
        const targetDateIndex = dates.findIndex(d => d === item.targetDate);

        if (targetRoomIndex === -1 || targetDateIndex === -1) return null;

        const statusConfig = RoomStatusManager.getStatusConfig(item.status);

        const targetX =
          config.roomTypeWidth +
          config.roomNumberWidth +
          targetDateIndex * config.cellWidth;
        const targetY = targetRoomIndex * config.cellHeight;

        return (
          <div
            key={`preview-${index}`}
            className={styles.targetPreview}
            style={{
              position: 'absolute',
              left: `${targetX}px`,
              top: `${targetY}px`,
              width: `${config.cellWidth}px`,
              height: `${config.cellHeight}px`,
              backgroundColor: statusConfig.backgroundColor,
              borderColor: statusConfig.borderColor,
              borderWidth: '2px',
              borderStyle: 'solid',
              borderRadius: '4px',
              opacity: 0.7,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '12px',
              fontWeight: 'bold',
              color: statusConfig.color,
              zIndex: 998,
              animation: 'pulse 1s ease-in-out infinite',
            }}
          >
            {statusConfig.icon}
          </div>
        );
      })}

      {/* 批量拖拽统计浮窗 */}
      <div className={styles.statsFloater}>
        <div className={styles.statsTitle}>📊 批量拖拽预览</div>
        <div className={styles.statsContent}>
          <div className={styles.statItem}>
            <span className={styles.statLabel}>源项目:</span>
            <span className={styles.statValue}>
              {batchDragState.sourceItems.length}
            </span>
          </div>
          <div className={styles.statItem}>
            <span className={styles.statLabel}>有效操作:</span>
            <span className={`${styles.statValue} ${styles.success}`}>
              {batchDragState.previewData.filter(item => item.isValid).length}
            </span>
          </div>
          {batchDragState.previewData.filter(item => !item.isValid).length >
            0 && (
            <div className={styles.statItem}>
              <span className={styles.statLabel}>冲突:</span>
              <span className={`${styles.statValue} ${styles.error}`}>
                {
                  batchDragState.previewData.filter(item => !item.isValid)
                    .length
                }
              </span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default BatchDragVisualizer;
